package com.example.config;

import com.example.entity.User;

import com.example.service.HotelService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private HotelService hotelService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //给用户进行授权
        SimpleAuthorizationInfo sim=new SimpleAuthorizationInfo();
        //拿到数据库的对象
        Subject subject = SecurityUtils.getSubject();
        User o =(User)subject.getPrincipal();
        sim.addStringPermission(o.getPerms());
        return sim;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {



        //从authenticationToken获取前端传来的数据
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        //让前端的数据与数据库的对比
        User user = hotelService.queryU(token.getUsername());

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        if(user==null){
            session.setAttribute("perms",null);
            return null;
        }

       session.setAttribute("id",user.getId());



     /*   Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("perms",user.getPerms());*/
       /* //获取session


        session.setAttribute("loginuser",user);
       ;*/




       /*
        if(session.getAttribute("loginuser")==null && "admin".equals(user.getPerms())){
                session.setAttribute("perms",user.getPerms());
            System.out.println("yyyyyyyyyyyy");

        }else {
            session.setAttribute("perms",null);
            System.out.println(session.getAttribute("loginuser")!=null);
        }*/

      /*  if("admin".equals(user.getPerms())&& "111".equals(user.getPassword())){
            session.setAttribute("perms",user.getPerms());
        }else {
            session.setAttribute("perms",null);
        }*/
        //密码shiro做
      /*  return new SimpleAuthenticationInfo(user,user.getPassword(),"");*/
        return  new SimpleAuthenticationInfo(user, user.getPassword(), "");


    }
}
